import tornado.ioloop
import tornado.web
import asyncio
import json
import com.gcteamo.coj.tools as tools
import com.gcteamo.coj.config as config


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write(r"https://pan.baidu.com/s/1mWvTp7BBPYeYrbsF9OLEqQ")

class LoginHandler(tornado.web.RequestHandler):
    async def post(self):
        try:
            config.logger.info("At LoginHandle -> " + self.request.path)
            obj=json.loads(self.request.body)
            ### print("{a} {b}".format(a=obj["user"],b=obj['password']))
            ### check
            status=200
            uid=await config.db.GetUid(obj["user"])
            if uid == -1:
                res = {"status": 401}
                self.write(json.dumps(res))
                return
            pwd=await config.db.GetUserPwd(uid)
            if pwd != obj['password']:
                res = {"status": 402}
                self.write(json.dumps(res))
                return

            ### success
            token=tools.md5_string(obj['password']+str(tools.get_time()))
            res={"status":200,"token":token}
            self.write(json.dumps(res))

        except Exception as e:
            config.logger.critical("At LoginHandle -> " + self.request.path + " : " +  str(e))
            res = {"status": 500}
            self.write(json.dumps(res))

async def Init():
    app=tornado.web.Application([
        (r"/",MainHandler),
        (r"/api/v2/login",LoginHandler)
    ])
    app.listen(15567)
    shutdown_event=asyncio.Event()
    await shutdown_event.wait()